var port = 3000;
var dataFile = './data/json.js';

var http = require('http');
var fs = require('fs');
var url = require('url');
var util = require('util');

var server = http.createServer(function(request, response){
	var path = url.parse(request.url).pathname;
	
	if(path == '/favicon.ico'){
		return;
	}
	
	var method = request.method.toLowerCase();
	util.log('accepted ' + request.url + ' with http method ' + method);
	
	var vname = path.replace(/\//g, '_');
	if(vname.startsWith('_')){
		vname = vname.substr(1);
	}
	
	var data = fs.readFileSync(dataFile, 'utf-8');
	
	eval(data);
	
	var vname0 = method + '_' + vname;
	
	var obj = {};
	try{
		util.log('loading with var name ' + vname0);
		obj = eval(vname0);
	}catch(e){
		try{
			util.log('no var name ' + vname0 + ' was found, use ' + vname + ' instead');
			obj = eval(vname);
		}catch(ee){
			console.error('neither ' + vname0 + ' nor ' + vname + ' was found');
			console.error(ee);
		}
	}
	
	var json = JSON.stringify(obj);
	
	util.log('json -> ' + json);
	
	response.write(json);
	response.end();
});

server.listen(port);
console.log('server was running at port ' + port);
